#include <iostream>
using namespace std;
#include <pthread.h>
#include <vector>
#include <unistd.h>

pthread_mutex_t gmutex = PTHREAD_MUTEX_INITIALIZER;
pthread_cond_t gcond = PTHREAD_COND_INITIALIZER;

void *MasterCore(void *args)
{
    sleep(3);
    cout << "master 开始工作 ..." << endl;

    while (true)
    {
        pthread_cond_signal(&gcond);
        cout << "master 正在唤醒一个线程" << endl;
        sleep(1);
    }
}

void *SlaverCore(void *args)
{
    string name = static_cast<const char *>(args);

    while (true)
    {
        pthread_mutex_lock(&gmutex); // 1. 加锁

        pthread_cond_wait(&gcond, &gmutex); // 2. 等待 释放锁
        cout << "当前被唤醒的线程: " << name << endl;

        pthread_mutex_unlock(&gmutex); // 3. 解锁
    }
}

void StartMaster(vector<pthread_t> *tidsptr)
{
    pthread_t tid;
    int n = pthread_create(&tid, nullptr, MasterCore, nullptr);
    if (n == 0)
    {
        cout << "create master success ..." << endl;
    }
    tidsptr->push_back(tid);
}

void StartSlaver(vector<pthread_t> *tidsptr, int threadnum = 3)
{
    for (int i = 0; i < threadnum; i++)
    {
        pthread_t tid;
        // string name = "thread-" + to_string(i + 1);
        // char name[64];
        char* name = new char[64];
        // snprintf(name, sizeof(name), "thread-%d", i+1); // sizeof(name) -- 4 bytes
        snprintf(name, 64, "thread-%d", i+1);
        int n = pthread_create(&tid, nullptr, SlaverCore, (void *)name);
        if (n == 0)
        {
            cout << "create thread success : " << name << endl;
            tidsptr->push_back(tid);
        }
    }
}

void WaitThread(vector<pthread_t> &tids)
{
    for (auto tid : tids)
    {
        pthread_join(tid, nullptr);
    }
}

int main()
{
    vector<pthread_t> tids;
    StartMaster(&tids);
    StartSlaver(&tids, 5);

    WaitThread(tids);
    return 0;
}